<template>
    <div class="common-layout">
      <el-container>
        <el-header>
          <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="患者姓名">
              <el-input v-model="formInline.Name" placeholder="请输入患者姓名" clearable />
            </el-form-item>
            <el-form-item label="随访方案">
              <el-select
                v-model="formInline.FollowUpPlan"
                placeholder="请选择随访方案"
                clearable
              >
                <el-option label="高血糖随访" value="高血糖随访" />
                <el-option label="高血压随访" value="高血压随访" />
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="状态">
              <el-select
                v-model="formInline.ScheduledFollowUpTime"
                placeholder="请选择状态"
                clearable
              >
                <el-option label="已超期" value="已超期" />
                <el-option label="未超期" value="未超期" />
              </el-select>
            </el-form-item> -->
            <el-form-item>
              <el-button type="primary" @click="onSubmit">查询</el-button>
              <el-button type="success" @click="dialogVisible = true">新增</el-button>
            </el-form-item>
          </el-form>
        </el-header>
        <el-main>
          <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
            <el-tab-pane label="未随访" name="first">
              <el-table :data="unfollowList" border style="width: 100%">
                <el-table-column type="index" label="序号" width="55" />
                <el-table-column prop="name" label="姓名" />
                <el-table-column prop="sex" label="性别" />
                <el-table-column prop="age" label="年龄" />
                <el-table-column prop="phoneNumber" label="联系电话" />
                <el-table-column prop="chronicVirusDisease" label="慢病病种" />
                <el-table-column prop="scheduledFollowUpTime" label="计划随访时间" >
                  <template #default="scope">
                    {{ scope.row.scheduledFollowUpTime.substring(0, 10) }}
                  </template>
                  </el-table-column>
                <el-table-column prop="followUpPlan" label="随访方案" />
                <el-table-column fixed="right" label="操作" min-width="120">
                  <template #default="scope">
                    <el-button
                      link
                      type="primary"
                      size="small"
                      @click="showFollowDialog(scope.row)"
                    >
                      随访
                    </el-button>
                    <el-button
                      link
                      type="primary"
                      size="small"
                      @click="showLostDialog(scope.row)"
                    >
                      失访
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="已随访" name="second">
              <el-table :data="followedList" border style="width: 100%">
                <el-table-column prop="name" label="姓名" />
                <el-table-column prop="sex" label="性别" />
                <el-table-column prop="age" label="年龄" />
                <el-table-column prop="phoneNumber" label="联系电话" />
                <el-table-column prop="chronicVirusDisease" label="慢病病种" />
                <el-table-column prop="scheduledFollowUpTime" label="计划随访时间" />
                <el-table-column prop="followUpPlan" label="随访方案" />
                <el-table-column prop="followUpTime" label="随访时间" />
                <el-table-column prop="follower" label="随访人" />
                <el-table-column prop="status" label="状态" />
                <el-table-column fixed="right" label="操作" min-width="120">
                  <template #default="scope">
                    <el-button link type="primary" size="small" @click="showDetail(scope.row)">
                      详情
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
  
          <!-- 新增弹出框 -->
          <el-dialog v-model="dialogVisible" title="新增随访管理" width="500">
            <span>
              <el-button type="primary" @click="dialogTableVisible = true">选择患者</el-button>
              <el-form :model="addform">
                <el-form-item label="姓名">
                  <el-input v-model="addform.name" placeholder="请输入姓名" clearable />
                </el-form-item>
                <el-form-item label="性别">
                  <el-input v-model="addform.sex" placeholder="请输入性别" clearable />
                </el-form-item>
                <el-form-item label="年龄">
                  <el-input v-model="addform.age" placeholder="请输入年龄" clearable />
                </el-form-item>
                <el-form-item label="慢病病种">
                  <el-input v-model="addform.chronicVirusDisease" placeholder="请输入慢病病种" clearable />
                </el-form-item>
                <el-form-item label="联系电话">
                  <el-input v-model="addform.phoneNumber" placeholder="请输入手机号" clearable />
                </el-form-item>
                <el-form-item label="随访时间">
                  <el-date-picker
        v-model="addform.scheduledFollowUpTime"
        type="date"
        placeholder="选择日期"
        clearable
      />
                </el-form-item>
                <el-form-item label="随访方案">
                  <el-select v-model="addform.followUpPlan" placeholder="请选择">
                    <el-option label="高血压随访" value="高血压随访" />
                    <el-option label="高血糖随访" value="高血糖随访" />
                  </el-select>
                </el-form-item>
              </el-form>
            </span>
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmAddPatient">确定</el-button>
              </div>
            </template>
          </el-dialog>
  
          <!-- 选择患者弹出框 -->
          <el-dialog v-model="dialogTableVisible" title="患者管理" width="800">
            <el-table :data="gridData" @selection-change="handleSelectionChange">
              <el-table-column type="selection" />
              <el-table-column property="residentFiles_Name" label="姓名" width="150" />
              <el-table-column property="sex" label="性别" width="100" />
              <el-table-column property="age" label="年龄" width="80" />
              <el-table-column property="phone" label="联系电话" width="150" />
              <el-table-column property="manageNCD" label="慢病病种" width="150" />
            </el-table>
            <template #footer>
              <el-button @click="dialogTableVisible = false">取消</el-button>
              <el-button type="primary" @click="confirmSelectPatient">确定</el-button>
            </template>
          </el-dialog>
  
          <!-- 随访弹出框 -->
          <el-dialog v-model="dialogFormVisible"  width="1000">
    <div class="hypertension-form">
      <h3 class="form-title">{{ isReadOnly ? '高血压随访记录详情' : '高血压一级管理随访记录表' }}</h3>
      <el-form :model="form" label-width="120px" class="form-container">
        <!-- 基本信息 -->
        <div class="form-row">
          <el-form-item label="姓名：" class="form-item">
            <el-input v-model="form.PatientName" placeholder="请输入姓名" class="underline-input" :disabled="isReadOnly"></el-input>
          </el-form-item>
          <el-form-item label="编号：" class="form-item">
            <el-input v-model="form.PatientNumber" class="underline-input" :disabled="isReadOnly"></el-input>
          </el-form-item>
        </div>
        
        <el-form-item label="随访日期" class="form-item">
          <el-date-picker
            v-model="form.FollowUpDate"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            class="underline-input"
            :disabled="isReadOnly"
          />
        </el-form-item>
        
        <el-form-item label="随访方式" class="form-item">
          <el-radio-group v-model="form.FollowUpMethod" class="radio-group" :disabled="isReadOnly">
            <el-radio label="门诊" class="custom-radio">门诊</el-radio>
            <el-radio label="家庭" class="custom-radio">家庭</el-radio>
            <el-radio label="电话" class="custom-radio">电话</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <!-- 症状 -->
        <el-form-item label="症状" class="form-item">
          <el-checkbox-group v-model="form.Symptoms" class="checkbox-group" :disabled="isReadOnly">
            <div class="symptom-row">
              <el-checkbox label="无症状" class="custom-checkbox">无症状</el-checkbox>
              <el-checkbox label="有症状" class="custom-checkbox">有症状</el-checkbox>
              <el-checkbox label="头痛" class="custom-checkbox">头痛</el-checkbox>
              <el-checkbox label="头晕" class="custom-checkbox">头晕</el-checkbox>
              <el-checkbox label="耳鸣" class="custom-checkbox">耳鸣</el-checkbox>
              <el-checkbox label="恶心" class="custom-checkbox">恶心</el-checkbox>
              <el-checkbox label="呕吐" class="custom-checkbox">呕吐</el-checkbox>
              <el-checkbox label="心悸" class="custom-checkbox">心悸</el-checkbox>
              <el-checkbox label="胸闷" class="custom-checkbox">胸闷</el-checkbox>
              <el-checkbox label="呼吸困难" class="custom-checkbox">呼吸困难</el-checkbox>
              <el-checkbox label="鼻出血不止" class="custom-checkbox">鼻出血不止</el-checkbox>
              <el-checkbox label="四肢发麻" class="custom-checkbox">四肢发麻</el-checkbox>
              <el-checkbox label="下肢水肿" class="custom-checkbox">下肢水肿</el-checkbox>
            </div>
          </el-checkbox-group>
        </el-form-item>
        
        <!-- 体征 -->
        <el-form-item label="血压(mmHg)" class="form-item">
          <div class="blood-pressure-input">
            <el-input v-model="form.BloodPressureSystolic" placeholder="请输入收缩压" class="underline-input small-input" :disabled="isReadOnly"></el-input>
            <span class="separator">/</span>
            <el-input v-model="form.BloodPressureDiastolic" placeholder="请输入舒张压" class="underline-input small-input" :disabled="isReadOnly"></el-input>
          </div>
        </el-form-item>
        
        <el-form-item label="体重(kg)" class="form-item">
          <div class="double-input">
            <el-input v-model="form.CurrentWeight" placeholder="请输入当前体重" class="underline-input small-input" :disabled="isReadOnly"></el-input>
            <span class="separator">/</span>
            <el-input v-model="form.TargetWeight" placeholder="请输入目标体重" class="underline-input small-input" :disabled="isReadOnly"></el-input>
          </div>
        </el-form-item>
        
        <el-form-item label="体质指数(kg/m²)" class="form-item">
          <div class="double-input">
            <el-input v-model="form.CurrentBMI" placeholder="请输入当前体质指数" class="underline-input small-input" :disabled="isReadOnly"></el-input>
            <span class="separator">/</span>
            <el-input v-model="form.TargetBMI" placeholder="请输入目标体质指数" class="underline-input small-input" :disabled="isReadOnly"></el-input>
          </div>
        </el-form-item>
        
        <el-form-item label="心率" class="form-item">
          <div class="double-input">
            <el-input v-model="form.CurrentHeartRate" placeholder="请输入当前心率" class="underline-input small-input" :disabled="isReadOnly"></el-input>
            <span class="separator">/</span>
            <el-input v-model="form.TargetHeartRate" placeholder="请输入目标心率" class="underline-input small-input" :disabled="isReadOnly"></el-input>
          </div>
        </el-form-item>
        
        <el-form-item label="其他" class="form-item">
          <el-input v-model="form.OtherConditions" placeholder="请输入其他情况" class="underline-input" :disabled="isReadOnly"></el-input>
        </el-form-item>
        
        <!-- 生活方式指导 -->
        <el-form-item label="日吸烟量" class="form-item">
          <div class="double-input">
            <el-input v-model="form.CurrentSmoking" placeholder="请输入当前吸烟量" class="underline-input small-input" :disabled="isReadOnly"></el-input>
            <span class="separator">/</span>
            <el-input v-model="form.TargetSmoking" placeholder="请输入目标吸烟量" class="underline-input small-input" :disabled="isReadOnly"></el-input>
            <span class="unit">支</span>
          </div>
        </el-form-item>
        
        <el-form-item label="日饮酒" class="form-item">
          <div class="double-input">
            <el-input v-model="form.CurrentAlcohol" placeholder="请输入当前饮酒量" class="underline-input small-input" :disabled="isReadOnly"></el-input>
            <span class="separator">/</span>
            <el-input v-model="form.TargetAlcohol" placeholder="请输入目标饮酒量" class="underline-input small-input" :disabled="isReadOnly"></el-input>
            <span class="unit">两</span>
          </div>
        </el-form-item>
        
        <el-form-item label="运动" class="form-item">
          <div class="exercise-input">
            <el-input v-model="form.CurrentExerciseFrequency" placeholder="请输入当前运动频次" class="underline-input small-input" :disabled="isReadOnly"></el-input>
            <span class="unit">次/周</span>
            <el-input v-model="form.CurrentExerciseDuration" placeholder="请输入当前运动时长" class="underline-input small-input" :disabled="isReadOnly"></el-input>
            <span class="unit">分钟/次</span>
          </div>
        </el-form-item>
        
        <el-form-item label="摄盐情况" class="form-item">
          <div class="radio-group-container">
            <div class="radio-subgroup">
              <span class="subgroup-label">目前：</span>
              <el-radio-group v-model="form.CurrentSaltIntake" class="radio-group" :disabled="isReadOnly">
                <el-radio label="轻(6g)" class="custom-radio">轻(6g)</el-radio>
                <el-radio label="中(6-12g)" class="custom-radio">中(6-12g)</el-radio>
                <el-radio label="重(>12g)" class="custom-radio">重(>12g)</el-radio>
              </el-radio-group>
            </div>
            <div class="radio-subgroup">
              <span class="subgroup-label">目标：</span>
              <el-radio-group v-model="form.TargetSaltIntake" class="radio-group" :disabled="isReadOnly">
                <el-radio label="轻(6g)" class="custom-radio">轻(6g)</el-radio>
                <el-radio label="中(6-12g)" class="custom-radio">中(6-12g)</el-radio>
                <el-radio label="重(>12g)" class="custom-radio">重(>12g)</el-radio>
              </el-radio-group>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="心理调整" class="form-item">
          <div class="radio-group-container">
            <div class="radio-subgroup">
              <span class="subgroup-label">目前：</span>
              <el-radio-group v-model="form.CurrentPsychological" class="radio-group" :disabled="isReadOnly">
                <el-radio label="良好" class="custom-radio">良好</el-radio>
                <el-radio label="一般" class="custom-radio">一般</el-radio>
                <el-radio label="差" class="custom-radio">差</el-radio>
              </el-radio-group>
            </div>
            <div class="radio-subgroup">
              <span class="subgroup-label">目标：</span>
              <el-radio-group v-model="form.TargetPsychological" class="radio-group" :disabled="isReadOnly">
                <el-radio label="良好" class="custom-radio">良好</el-radio>
                <el-radio label="一般" class="custom-radio">一般</el-radio>
                <el-radio label="差" class="custom-radio">差</el-radio>
              </el-radio-group>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="遵医行为" class="form-item">
          <div class="radio-group-container">
            <div class="radio-subgroup">
              <span class="subgroup-label">目前：</span>
              <el-radio-group v-model="form.CurrentCompliance" class="radio-group" :disabled="isReadOnly">
                <el-radio label="良好" class="custom-radio">良好</el-radio>
                <el-radio label="一般" class="custom-radio">一般</el-radio>
                <el-radio label="差" class="custom-radio">差</el-radio>
              </el-radio-group>
            </div>
            <div class="radio-subgroup">
              <span class="subgroup-label">目标：</span>
              <el-radio-group v-model="form.TargetCompliance" class="radio-group" :disabled="isReadOnly">
                <el-radio label="良好" class="custom-radio">良好</el-radio>
                <el-radio label="一般" class="custom-radio">一般</el-radio>
                <el-radio label="差" class="custom-radio">差</el-radio>
              </el-radio-group>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="服药依从性" class="form-item">
          <div class="radio-group-container">
            <div class="radio-subgroup">
              <span class="subgroup-label">目前：</span>
              <el-radio-group v-model="form.CurrentMedication" class="radio-group" :disabled="isReadOnly">
                <el-radio label="规律" class="custom-radio">规律</el-radio>
                <el-radio label="间断" class="custom-radio">间断</el-radio>
                <el-radio label="不服药" class="custom-radio">不服药</el-radio>
              </el-radio-group>
            </div>
            <div class="radio-subgroup">
              <span class="subgroup-label">目标：</span>
              <el-radio-group v-model="form.TargetMedication" class="radio-group" :disabled="isReadOnly">
                <el-radio label="规律" class="custom-radio">规律</el-radio>
                <el-radio label="间断" class="custom-radio">间断</el-radio>
                <el-radio label="不服药" class="custom-radio">不服药</el-radio>
              </el-radio-group>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="药物不良反应" class="form-item">
          <el-radio-group v-model="form.AdverseDrugReaction" class="radio-group" :disabled="isReadOnly">
            <el-radio label="无" class="custom-radio">无</el-radio>
            <el-radio label="有" class="custom-radio">有</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="低血糖反应" class="form-item">
          <el-radio-group v-model="form.HypoglycemicReaction" class="radio-group" :disabled="isReadOnly">
            <el-radio label="无" class="custom-radio">无</el-radio>
            <el-radio label="偶尔" class="custom-radio">偶尔</el-radio>
            <el-radio label="频繁" class="custom-radio">频繁</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="此次随访分类" class="form-item">
          <el-radio-group v-model="form.FollowUpClassification" class="radio-group" :disabled="isReadOnly">
            <el-radio label="控制满意" class="custom-radio">控制满意</el-radio>
            <el-radio label="控制不满意" class="custom-radio">控制不满意</el-radio>
            <el-radio label="不良反应" class="custom-radio">不良反应</el-radio>
            <el-radio label="并发症" class="custom-radio">并发症</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 用药情况 -->
        <el-form-item label="药物名称1" class="form-item">
          <div class="medication-row">
            <el-input v-model="form.DrugName1" placeholder="请输入药物名称" class="underline-input" :disabled="isReadOnly"></el-input>
            <span class="medication-label">用法：</span>
            <el-input v-model="form.DrugDose1" placeholder="请输入用法" class="underline-input small-input" :disabled="isReadOnly"></el-input>
            <span class="medication-label">用量：</span>
            <el-input v-model="form.DrugUsage1" placeholder="请输入用量" class="underline-input small-input" :disabled="isReadOnly"></el-input>
          </div>
        </el-form-item>
        
        <el-form-item label="药物名称2" class="form-item">
          <div class="medication-row">
            <el-input v-model="form.DrugName2" placeholder="请输入药物名称" class="underline-input" :disabled="isReadOnly"></el-input>
            <span class="medication-label">用法：</span>
            <el-input v-model="form.DrugDose2" placeholder="请输入用法" class="underline-input small-input" :disabled="isReadOnly"></el-input>
            <span class="medication-label">用量：</span>
            <el-input v-model="form.DrugUsage2" placeholder="请输入用量" class="underline-input small-input" :disabled="isReadOnly"></el-input>
          </div>
        </el-form-item>
        
        <el-form-item label="药物名称3" class="form-item">
          <div class="medication-row">
            <el-input v-model="form.DrugName3" placeholder="请输入药物名称" class="underline-input" :disabled="isReadOnly"></el-input>
            <span class="medication-label">用法：</span>
            <el-input v-model="form.DrugDose3" placeholder="请输入用法" class="underline-input small-input" :disabled="isReadOnly"></el-input>
            <span class="medication-label">用量：</span>
            <el-input v-model="form.DrugUsage3" placeholder="请输入用量" class="underline-input small-input" :disabled="isReadOnly"></el-input>
          </div>
        </el-form-item>
        
        <el-form-item label="药物名称4" class="form-item">
          <div class="medication-row">
            <el-input v-model="form.DrugName4" placeholder="请输入药物名称" class="underline-input" :disabled="isReadOnly"></el-input>
            <span class="medication-label">用法：</span>
            <el-input v-model="form.DrugDose4" placeholder="请输入用法" class="underline-input small-input" :disabled="isReadOnly"></el-input>
            <span class="medication-label">用量：</span>
            <el-input v-model="form.DrugUsage4" placeholder="请输入用量" class="underline-input small-input" :disabled="isReadOnly"></el-input>
          </div>
        </el-form-item>
        
        <!-- 转诊 -->
        <el-form-item label="转诊" class="form-item">
          <div class="referral-container">
            <div class="referral-row">
              <span class="referral-label">原因：</span>
              <el-input v-model="form.ReferralReason" placeholder="请输入转诊原因" class="underline-input" :disabled="isReadOnly"></el-input>
            </div>
            <div class="referral-row">
              <span class="referral-label">机构及科别：</span>
              <el-input v-model="form.ReferralInstitution" placeholder="请输入转入机构及科室" class="underline-input" :disabled="isReadOnly"></el-input>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="下次随访时间" class="form-item">
          <el-date-picker
            v-model="form.NextFollowUpDate"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            class="underline-input"
            :disabled="isReadOnly"
          />
        </el-form-item>
        
        <el-form-item label="随访医生签名" class="form-item">
          <el-input v-model="form.DoctorSignature" placeholder="请输入医生签名" class="underline-input" :disabled="isReadOnly"></el-input>
        </el-form-item>
      </el-form>
      
      <div class="form-buttons">
        <el-button type="primary" class="btn btn-primary" v-if="!isReadOnly">预约门诊</el-button>
        <el-button class="btn" v-if="!isReadOnly">清空</el-button>
        <el-button type="primary" class="btn btn-save" @click="save" v-if="!isReadOnly">保存</el-button>
        <el-button @click="dialogFormVisible = false" v-if="isReadOnly">关闭</el-button>
      </div>
    </div>
  </el-dialog>
          <!-- 失访登记弹出框 -->
          <el-dialog v-model="lostDialogVisible" title="失访登记" width="500">
            <div>
              <el-row>
                <el-col :span="12">
                  <el-avatar :size="50" :src="currentLostPatient || ''" />
                  <div>
                    <p>{{ currentLostPatient.name }}</p>
                    <p>性别：{{ currentLostPatient.sex }}</p>
                    <p>年龄：{{ currentLostPatient.age }}</p>
                    <p>联系电话：{{ currentLostPatient.phoneNumber }}</p>
                    <p>慢病病种：{{ currentLostPatient.chronicVirusDisease }}</p>
                  </div>
                </el-col>
              </el-row>
              <el-form :model="lostForm">
                <el-form-item label="失访原因">
                  <el-select v-model="lostForm.lossToFollowUpReason" placeholder="请选择">
                    <el-option label="死亡" value="死亡" />
                    <el-option label="去往外地" value="去往外地" />
                  </el-select>
                </el-form-item>
                <el-form-item label="备注">
                  <el-input v-model="lostForm.remarks" type="textarea" />
                </el-form-item>
              </el-form>
            </div>
            <template #footer>
              <el-button @click="lostDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="confirmLost">保存</el-button>
            </template>
          </el-dialog>
        </el-main>
      </el-container>
    </div>
  </template>
  
  <script lang="ts" setup>
  import { onMounted, reactive, ref } from 'vue';
  import { ElMessageBox, ElMessage} from 'element-plus';
  import axios from 'axios';
  import { useCounterStore } from '@/stores/counter';
  const apiUrl = import.meta.env.VITE_APP_API_URL;
  const store = useCounterStore();
  // 未随访列表
  const unfollowList = ref([
    // 初始数据
  ]);
  // 已随访列表
  const followedList = ref([
    // 初始数据
  ]);
  
  // 新增弹出框
  const dialogVisible = ref(false);
  const addform = ref({
    name: '',
    sex: '',
    age: '',
    chronicVirusDisease: '',
    phoneNumber: '',
    scheduledFollowUpTime: '',
    followUpPlan: '',
    lossToFollowUpReason: '',
    remarks: '',
    status:'',
    followUpTime:'2023-01-01',
    upName:'',
  });
  
  // 选择患者弹出框
  const dialogTableVisible = ref(false);
  const gridData = ref([
    {
      name: '陈斌',
      sex: '男',
      age: 64,
      phoneNumber: '15595467889',
      chronicVirusDisease: '高血压'
    }, {
      name: '周世杰',
      sex: '男',
      age: 180,
      phoneNumber: '15585467889',
      chronicVirusDisease: '高血糖'
    },
    // 其他患者数据
  ]);
  const selectedRows = ref<any[]>([]);
  const handleSelectionChange = (rows: any[]) => {
    selectedRows.value = rows;
  };
  const confirmSelectPatient = () => {
    if (selectedRows.value.length > 0) {
      const patient = selectedRows.value[0];
      addform.value.name = patient.residentFiles_Name;
      addform.value.sex = patient.sex;
      addform.value.age = patient.age;
      addform.value.phoneNumber = patient.phone;
      addform.value.chronicVirusDisease = patient.manageNCD;
    }
    dialogTableVisible.value = false;
  };
  
  // 确认新增患者
  const confirmAddPatient = () => {
    axios.post(apiUrl+'/T8/Management/AddBasic',addform.value).then(res=>{
      console.log(res);
      if(res.data.code==212){
        ElMessage.success('新增成功');
        dialogVisible.value = false;
    getUnfollowList();
      }else{
        ElMessage.error('新增失败');
      }
    })
    // const newPatient = {
    //   name: addform.value.name,
    //   sex: addform.value.sex,
    //   age: addform.value.age,
    //   phoneNumber: addform.value.phoneNumber,
    //   chronicVirusDisease: addform.value.chronicVirusDisease,
    //   scheduledFollowUpTime: addform.value.scheduledFollowUpTime,
    //   followUpPlan: addform.value.followUpPlan,
    //   status: '未随访'
    // };
    // unfollowList.value.push(addform.value);
  };
  //未随访表格
  const page=reactive({
    totalCount:0,
    totalPage:0,
    PageIndex:1,
    PageSize:10
  })

  const getUnfollowList = () => {
    axios.get(apiUrl+'/T7/Management/GetBasic',{params:{Name:formInline.Name,FollowUpPlan:formInline.FollowUpPlan,ScheduledFollowUpTime:formInline.ScheduledFollowUpTime,PageIndex:page.PageIndex,PageSize:page.PageSize}}).then(res=>{
      console.log(res.data.data.list);
      unfollowList.value = res.data.data.list;
      page.totalCount = res.data.data.totalCount;
      page.totalPage = res.data.data.totalPage;
    })
  };
  //已随访表格
  const getFollowList = () => {
    axios.get(apiUrl+'/T7/Management/GetBasicFollow',{params:{Name:formInline.Name,FollowUpPlan:formInline.FollowUpPlan,ScheduledFollowUpTime:formInline.ScheduledFollowUpTime,PageIndex:page.PageIndex,PageSize:page.PageSize}}).then(res=>{
     
      followedList.value = res.data.data.list;
      
      page.totalCount = res.data.data.totalCount;
      page.totalPage = res.data.data.totalPage;
    })
  };

  //随访弹出框
  const dialogFormVisible = ref(false)
  const isReadOnly = ref(false); // 控制表单是否只读
  const form = ref({
    BasicId: 0,
    RecordId: 0,
    PatientName:'',
    PatientNumber: '',
    FollowUpDate:new Date(),
    FollowUpMethod: '',
    Symptoms: [],
    BloodPressureSystolic: '',
    BloodPressureDiastolic: '',
    CurrentWeight: '',
    TargetWeight: '',
    CurrentBMI: '',
    TargetBMI: '',
    CurrentHeartRate: '',
    TargetHeartRate: '',
    OtherConditions: '',
    CurrentSmoking: '',
    TargetSmoking: '',
    CurrentAlcohol: '',
    TargetAlcohol: '',
    CurrentExerciseFrequency: '',
    CurrentExerciseDuration: '',
    CurrentSaltIntake: '',
    TargetSaltIntake: '',
    CurrentPsychological: '',
    TargetPsychological: '',
    CurrentCompliance: '',
    TargetCompliance: '',
    CurrentMedication: '',
    TargetMedication: '',
    AdverseDrugReaction: '',
    HypoglycemicReaction: '',
    FollowUpClassification: '',
    DrugName1: '',
    DrugDose1: '',
    DrugUsage1: '',
    DrugName2: '',
    DrugDose2: '',
    DrugUsage2: '',
    DrugName3: '',
    DrugDose3: '',
    DrugUsage3: '',
    DrugName4: '',
    DrugDose4: '',
    DrugUsage4: '',
    ReferralReason: '',
    ReferralInstitution: '',
    NextFollowUpDate: '',
    DoctorSignature: store.ccstore.nickName,
  });
  const save=(row:any)=>{
    const forms:any={...form.value}
    if(Array.isArray(forms.Symptoms) && forms.Symptoms.length>0){
      forms.Symptoms=forms.Symptoms.join(',')
    }else{
      forms.Symptoms=''
    }
    axios.post(apiUrl+'/T8/Management/AddFollow',forms).then(res=>{
      console.log(res)
      if(res.data.code==212){
        ElMessage.success("提交成功")
        dialogFormVisible.value=false
        // 刷新已随访列表
        getFollowList();
        // 切换到已随访标签
        activeName.value = 'second';
        // 刷新未随访列表
        getUnfollowList();
      }else{
        ElMessage.error("提交失败") 
      }
    })
  }
 
  const showFollowDialog = (row: any) => {
    form.value.BasicId = row.basicId;
    form.value.PatientName = row.name;
    isReadOnly.value = false; // 新增随访时表单可编辑
    dialogFormVisible.value = true;
  };
  
  // 失访登记
  const lostDialogVisible = ref(false);
  const currentLostPatient = ref<any>({});
  const lostForm = reactive({
    basicId: 0,
    lossToFollowUpReason: '',
    remarks: '',
    status:'',
    followUpTime:'2025-05-05',
    upName:store.ccstore.nickName
  });
  const showLostDialog = (row:any) => {
    // currentLostPatient.value = {
    //   ...row,
    // };
   
    lostForm.basicId = row.basicId;
    currentLostPatient.value = row;
    lostDialogVisible.value = true;
  };
  const confirmLost = () => {
    axios.put(apiUrl+'/T8/Management/Handle',lostForm ).then((res) => {
      if(res.data.data==1){
        ElMessage.success('失访成功');
        lostDialogVisible.value = false;
        getUnfollowList();
      }else{
        ElMessage.error('失访失败');
      }
    })
    // unfollowList.value = unfollowList.value.filter(row => row !== currentLostPatient.value);
    // currentLostPatient.value.status = '失访';
    // currentLostPatient.value.lostReason = lostForm.value.reason;
    // currentLostPatient.value.remark = lostForm.value.remark;
    //followedList.value.push(currentLostPatient.value);
    lostDialogVisible.value = false;
  };
  const showDetail = (row: any) => {
    console.log('查看详情，行数据:', row);
    if (row.status === '已随访') {
      isReadOnly.value = true; // 查看详情时表单只读
      dialogFormVisible.value = true;
      
      // 清空表单数据并设置基本信息
      resetFollowForm();
      form.value.BasicId = row.basicId;
      form.value.PatientName = row.name;
      
      console.log(`正在请求随访详情数据，BasicId=${row.basicId}`);
      
      // 尝试使用不同格式的API请求
      axios
        .get(apiUrl+'/T7/Management/GetFollow', {
          params: { BasicId: row.basicId }
        })
        .then((res) => {
          console.log('API响应数据:', res.data);
          
          if (res.data.code === 210 && res.data.data) {
            processFollowUpData(res.data.data, row);
            form.value.BasicId = res.data.data[0].basicId
                  form.value.PatientName = res.data.data[0].patientName
                  form.value.FollowUpDate = res.data.data[0].followUpDate
                  form.value.FollowUpMethod = res.data.data[0].followUpMethod
                  form.value.Symptoms = res.data.data[0].symptoms.split(',')
                  form.value.BloodPressureSystolic = res.data.data[0].bloodPressureSystolic
                  form.value.BloodPressureDiastolic = res.data.data[0].bloodPressureDiastolic
                  form.value.CurrentWeight = res.data.data[0].currentWeight
                  form.value.TargetWeight = res.data.data[0].targetWeight
                  form.value.CurrentBMI = res.data.data[0].currentBMI
                  form.value.TargetBMI = res.data.data[0].targetBMI
                  form.value.CurrentHeartRate = res.data.data[0].currentHeartRate
                  form.value.TargetHeartRate = res.data.data[0].targetHeartRate
                  form.value.OtherConditions = res.data.data[0].otherConditions
                  form.value.CurrentSmoking = res.data.data[0].currentSmoking
                  form.value.TargetSmoking = res.data.data[0].targetSmoking
                  form.value.CurrentAlcohol = res.data.data[0].currentAlcohol
                  form.value.TargetAlcohol = res.data.data[0].targetAlcohol
                  form.value.CurrentExerciseFrequency = res.data.data[0].currentExerciseFrequency
                  form.value.CurrentExerciseDuration = res.data.data[0].currentExerciseDuration
                  form.value.CurrentSaltIntake = res.data.data[0].currentSaltIntake
                  form.value.TargetSaltIntake = res.data.data[0].targetSaltIntake
                  form.value.CurrentPsychological = res.data.data[0].currentPsychological
                  form.value.TargetPsychological = res.data.data[0].targetPsychological
                  form.value.CurrentCompliance = res.data.data[0].currentCompliance
                  form.value.TargetCompliance = res.data.data[0].targetCompliance
                  form.value.CurrentMedication = res.data.data[0].currentMedication
                  form.value.TargetMedication = res.data.data[0].targetMedication
                  form.value.AdverseDrugReaction = res.data.data[0].adverseDrugReaction
                  form.value.HypoglycemicReaction = res.data.data[0].hypoglycemicReaction
                  form.value.FollowUpClassification = res.data.data[0].followUpClassification
                  form.value.DrugName1 = res.data.data[0].drugName1
                  form.value.DrugDose1 = res.data.data[0].drugDose1
                  form.value.DrugUsage1 = res.data.data[0].drugUsage1
                  form.value.DrugName2 = res.data.data[0].drugName2
                  form.value.DrugDose2 = res.data.data[0].drugDose2
                  form.value.DrugUsage2 = res.data.data[0].drugUsage2
                  form.value.DrugName3 = res.data.data[0].drugName3
                  form.value.DrugDose3 = res.data.data[0].drugDose3
                  form.value.DrugUsage3 = res.data.data[0].drugUsage3
                  form.value.DrugName4 = res.data.data[0].drugName4
                  form.value.DrugDose4 = res.data.data[0].drugDose4
                  form.value.DrugUsage4 = res.data.data[0].drugUsage4
                  form.value.ReferralReason = res.data.data[0].referralReason
                  form.value.ReferralInstitution = res.data.data[0].referralInstitution
                  form.value.NextFollowUpDate = res.data.data[0].nextFollowUpDate
                  form.value.DoctorSignature = res.data.data[0].doctorSignature
          } else {
            console.error('API返回错误:', res.data.msg);
            ElMessage.warning(res.data.msg || '未找到该随访记录的详细信息');
            
            // 如果第一种请求方式失败，尝试使用第二种方式
            console.log('尝试使用第二种API请求格式');
            axios
              .get(apiUrl+'/T7/Management/GetFollow' ,{
                params: { BasicId: row.basicId }
              })
              .then((res2) => {
                console.log('第二次API响应数据:', res2.data);
                if (res2.data.code === 210 && res2.data.data) {
                  processFollowUpData(res2.data.data, row);
                }
              })
              .catch(error => {
                console.error('第二次获取随访记录失败', error);
              });
          }
        })
        .catch(error => {
          console.error('获取随访记录失败', error);
          ElMessage.error('获取随访记录失败');
        });
    } else {
      lostForm.basicId = row.basicId;
      currentLostPatient.value = row;
      lostDialogVisible.value = true;
      lostForm.lossToFollowUpReason = row.lossToFollowUpReason;
      lostForm.remarks = row.remarks;
    }
  };

  // 辅助函数：清空和重置随访表单
  const resetFollowForm = () => {
    // 清空所有表单字段
    for (const key in form.value) {
      if (Object.prototype.hasOwnProperty.call(form.value, key)) {
        // 根据字段类型设置不同的默认值
        if (key === 'Symptoms') {
          form.value.Symptoms = [];
        } else if (key === 'BasicId' || key === 'RecordId') {
          form.value[key] = 0;
        } else if (key === 'FollowUpDate') {
          form.value[key] = new Date();
        } else if (key === 'DoctorSignature') {
          form.value[key] = store.ccstore.nickName;
        } else {
          (form.value as any)[key] = '';
        }
      }
    }
  };

  // 辅助函数：处理API返回的随访数据
  const processFollowUpData = (formData: any, row: any) => {
    console.log('处理随访数据:', formData);
    
    // 检查数据格式，如果API返回的是嵌套结构，使用正确的数据对象
    if (formData.followRecord && typeof formData.followRecord === 'object') {
      console.log('检测到嵌套的followRecord数据结构');
      formData = formData.followRecord;
    } else if (formData.data && typeof formData.data === 'object') {
      console.log('检测到嵌套的data数据结构');
      formData = formData.data;
    }
    
    // 定义字段映射关系（API字段名 -> 表单字段名）
    const fieldMappings: Record<string, string> = {
      // 基本信息字段
      patientName: 'PatientName',
      patientNumber: 'PatientNumber',
      followUpDate: 'FollowUpDate',
      followUpMethod: 'FollowUpMethod',
      symptoms: 'Symptoms',
      
      // 其他可能不一致的字段
      
      basicId: 'BasicId',
      recordId: 'RecordId',
      // ... 其他可能的映射
    };
    
    // 先处理Symptoms字段，将字符串转换为数组
    if (typeof formData.symptoms === 'string' && formData.symptoms) {
      form.value.Symptoms = formData.symptoms.split(',');
    } else if (typeof formData.Symptoms === 'string' && formData.Symptoms) {
      form.value.Symptoms = formData.Symptoms.split(',');
    } else {
      form.value.Symptoms = [];
    }
    
    // 遍历API响应数据
    for (const key in formData) {
      if (Object.prototype.hasOwnProperty.call(formData, key) && key !== 'symptoms') {
        // 获取正确的表单字段名
        let formKey = fieldMappings[key] || (key.charAt(0).toUpperCase() + key.slice(1));
        
        // 输出调试信息
        console.log(`处理字段 ${key} -> ${formKey}, 值:`, formData[key]);
        
        // 忽略null和undefined值
        if (formData[key] === null || formData[key] === undefined) {
          continue;
        }
        
        // 特殊处理日期字段
        if ((key.toLowerCase().includes('date') || formKey.toLowerCase().includes('date')) && formData[key]) {
          try {
            // 确保日期格式正确
            (form.value as any)[formKey] = formData[key].substring(0, 10);
          } catch (e) {
            console.error(`处理日期字段 ${key} 失败:`, e);
            (form.value as any)[formKey] = formData[key];
          }
        } else {
          (form.value as any)[formKey] = formData[key];
        }
      }
    }
    
    // 确保基本信息正确
    form.value.BasicId = row.basicId;
    form.value.PatientName = row.name;
    
    console.log('表单反填完成，当前表单数据:', form.value);
  };

  // 搜索条件
  const formInline = reactive({
    Name: '',
    FollowUpPlan: '',
    ScheduledFollowUpTime: ''
  });
  
  const onSubmit = () => {
    getUnfollowList();
  };
  //人员管理
  const chaForm = reactive({
      CreateStartTime: "",
      CreateEndTime: "",
      ResidentFiles_Name: "",
      ResidentFiles_Id: 0,
      Team: null,
      Doctor_Name: '',
      PageIndex: 1,
      PageSize: 15
    })

    const pages = reactive({
      pageIndex: 1,
      pageSize: 15,
      totalCount: 0,
      totalPage: 0
    })
  const getSignData = async () => {
      try {
        const res = await axios.get(apiUrl+'/T7/Sign/GetResidentFilesList', {
          params: {
            PageIndex: pages.pageIndex,
            PageSize: pages.pageSize,
            CreateStartTime: chaForm.CreateStartTime,
            CreateEndTime: chaForm.CreateEndTime,
            ResidentFiles_Name: chaForm.ResidentFiles_Name,
            ResidentFiles_Id: chaForm.ResidentFiles_Id,
            Team: chaForm.Team,
            Doctor_Name: chaForm.Doctor_Name,
          }
        })
        gridData.value = res.data.list
        page.totalCount = res.data.totalCount
        page.totalPage = res.data.totalPage
      } catch (error) {
        ElMessage.error('获取签约数据失败')
      }
    }

  const activeName = ref('first');
  const handleClick = (tab: any, event: any) => {
    console.log(tab, event);
  };
  onMounted(() => {
    getUnfollowList();
    getFollowList();
    getSignData()
  })
  </script> 
  
  <style>
  .demo-form-inline .el-input {
    --el-input-width: 220px;
  }
  
  .demo-form-inline .el-select {
    --el-select-width: 220px;
  }
  .demo-form-inline .el-input {
    --el-input-width: 220px;
  }
  
  .demo-form-inline .el-select {
    --el-select-width: 220px;
  }
  </style>
  <style scoped>
  .hypertension-form {
    width: 100%;
    max-width: 900px;
    margin: 0 auto;
    padding: 20px;
    background-color: white;
    font-family: Arial, sans-serif;
  }
  
  .form-title {
    text-align: center;
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 20px;
    color: #333;
  }
  
  .form-container {
    width: 100%;
  }
  
  .form-row {
    display: flex;
    justify-content: space-between;
  }
  
  .form-item {
    margin-bottom: 10px;
  }
  
  .underline-input {
    :deep(.el-input__inner) {
      border: none;
      border-bottom: 1px solid #dcdfe6;
      border-radius: 0;
      padding: 0;
      height: 32px;
      line-height: 32px;
    }
  }
  
  .small-input {
    width: 100px;
  }
  
  .blood-pressure-input,
  .double-input,
  .exercise-input {
    display: flex;
    align-items: center;
  }
  
  .separator {
    margin: 0 5px;
  }
  
  .unit {
    margin-left: 5px;
    color: #666;
  }
  
  .checkbox-group {
    display: flex;
    flex-direction: column;
  }
  
  .symptom-row {
    margin-bottom: 5px;
  }
  
  .custom-checkbox {
    margin-right: 15px;
  }
  
  .custom-checkbox :deep(.el-checkbox__label) {
    font-weight: normal;
  }
  
  .radio-group {
    display: flex;
    flex-wrap: wrap;
  }
  
  .radio-group-container {
    display: flex;
    flex-direction: column;
  }
  
  .radio-subgroup {
    display: flex;
    margin-bottom: 5px;
  }
  
  .subgroup-label {
    margin-right: 10px;
    line-height: 32px;
  }
  
  .custom-radio {
    margin-right: 15px;
  }
  
  .custom-radio :deep(.el-radio__label) {
    font-weight: normal;
  }
  
  .medication-row {
    display: flex;
    align-items: center;
  }
  
  .medication-label {
    margin: 0 10px;
  }
  
  .referral-container {
    display: flex;
    flex-direction: column;
  }
  
  .referral-row {
    display: flex;
    align-items: center;
    margin-bottom: 5px;
  }
  
  .referral-label {
    margin-right: 10px;
  }
  
  .form-buttons {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }
  
  .btn {
    margin-left: 10px;
  }
  
  .btn-primary {
    background-color: #4CAF50;
    border-color: #4CAF50;
  }
  
  .btn-save {
    background-color: #2196F3;
    border-color: #2196F3;
  }
  </style>
